package com.gyh.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyh.entity.Course;
import com.gyh.entity.Member;
import com.gyh.service.MemberService;
import com.gyh.util.JWTUtil;
import com.gyh.util.Result;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private MemberService memberService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        /*判断token是否存在*/
        if (!StringUtils.hasText(token)){
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(401,"未登录")));
            return false;
        }
        /*验证token*/
        Member member = null;
        try{
            Claims claims = JWTUtil.parseJWT(token);
            String phone = claims.getSubject();
            QueryWrapper<Member> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            member = memberService.getOne(wrapper);
        }catch (Exception e){
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(401,"token失效")));
            return false;
        }
        if (ObjectUtil.isEmpty(member)){
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(401,"账号或密码不存在")));
            return false;
        }
        /*刷新token*/
        token = JWTUtil.createJWT(member.getPhone());
        response.setHeader("token",token);
        return  true;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
